//
//  ViewForHeader.m
//  A段项目
//
//  Created by dllo on 16/1/29.
//  Copyright © 2016年 Scott. All rights reserved.
//

#import "ViewForHeader.h"
#import "LbtCell.h"
#import "FirstStyleCell.h"
#import "SecondStyleCellForOnce.h"

#import "NetWorkingHandler.h"
#import "Model.h"
#import <UIImageView+WebCache.h>
#import "LbtWebView.h"
#import "ViewController.h"

#import "AppEndCacheData.h"




@interface ViewForHeader ()<UITableViewDelegate,UITableViewDataSource,LbtCellDelegate>

@property (nonatomic, retain) NSMutableArray *arrModel;
@property (nonatomic, retain) UIImageView *imageView;
@property (nonatomic, retain) LbtCell *cell;

@end

@implementation ViewForHeader


- (void)dealloc {
    
     [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    self.cell.delegate = nil;
    [_tableView release];
    [_imageView release];
    
    self.cell.delegate = nil;
    
    [super dealloc];
    
}




- (instancetype) initWithFrame:(CGRect)frame {
    
    self = [super initWithFrame:frame];
    
    if (self) {
        
        [self appBegain];
        
         [self handleData];
        
        /**下拉刷新.*/
        [[NSNotificationCenter defaultCenter] addObserverForName:@"refresh" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
            
            [self handleData]; //接收 VC 发来的"进行了刷新的通知."
            
        }];
        
        self.backgroundColor = [UIColor blueColor];
        
        self.tableView = [[UITableView alloc] initWithFrame:self.bounds style:UITableViewStylePlain];
               
        self.tableView.backgroundColor = [UIColor whiteColor];
        
        self.tableView.separatorStyle = 0;
       
        
        [self cacheData];
        
           self.tableView.separatorColor = [UIColor whiteColor];
        
        self.tableView.sectionIndexBackgroundColor = [UIColor whiteColor];
        
        [self addSubview:self.tableView];
        
        [self cacheData];
        
    }
    
    return self;
    
}



- (void)handleData {
    

        [NetWorkingHandler netWorkingWithUrl:@"http://mapp.tiankong.com/index/v1.1" complete:^(id result) {
            
            self.arrModel = [NSMutableArray array];
            
            NSArray *arr = [result objectForKey:@"data"];
            
            for (NSDictionary *dic in arr) {
                
                
                Model *modle = [[Model alloc] init];
                
                [modle setValuesForKeysWithDictionary:dic];
                
                [self.arrModel addObject:modle];
                
                [modle release];
                
            }
        
            [self.tableView reloadData];
            
            /**执行代理方法.传高度值. */
             [self.delegate highetForHeaderView:self.tableView.contentSize.height];
            
        }];
        
    
    
    
}

- (void)layoutSubviews {
    
    [super layoutSubviews];
  
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    self.tableView.bounces = NO;
    
    [self.tableView registerClass:[LbtCell class] forCellReuseIdentifier:@"pool1"];
    
    [self.tableView registerClass:[FirstStyleCell class] forCellReuseIdentifier:@"pool2"];
    
    [self.tableView registerClass:[SecondStyleCellForOnce class] forCellReuseIdentifier:@"pool3"];
    
    [self.tableView registerClass:[UITableViewHeaderFooterView class] forHeaderFooterViewReuseIdentifier:@"headerPool"];
    
    
    
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
  
    
    return self.arrModel.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    Model *modle = [self.arrModel objectAtIndex:indexPath.section];

#pragma mark -- 判断 cell 的类型
    
    /**第一行的轮播图.*/
    if (modle.style == 4) {
        
        self.cell = [tableView dequeueReusableCellWithIdentifier:@"pool1"];
        
        self.cell.delegate = self;
        
        [self.cell passedImageNumber:modle.data.count];
        
        for (int i = 0; i < modle.data.count; i ++) {
            
            NSDictionary *dic = [modle.data objectAtIndex:i];
           
            Model *modelPic = [[Model alloc] init];
            
            [modelPic setValuesForKeysWithDictionary:dic];
            
            self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(i *self.bounds.size.width, 0, self.bounds.size.width,200)];
            
            [self.imageView sd_setImageWithURL:[NSURL URLWithString:modelPic.imageUrl]];
            
            self.imageView.userInteractionEnabled = YES;
            
            [self.cell.scroll addSubview:self.imageView];
            
            [_imageView release];
            
            [modelPic release];
            
        }
        
        return self.cell;
    }else if (modle.style == 1)  //第二行的类型
    {
        
        
        FirstStyleCell *cell = [tableView dequeueReusableCellWithIdentifier:@"pool2"];
        
        cell.arrData = [NSArray arrayWithArray:modle.data];
                
        cell.dicForType = [NSString stringWithString:modle.sourceData];
        
      
        
        return cell;
    }else {
        
        /**第三种类型. */
        SecondStyleCellForOnce *cell = [tableView dequeueReusableCellWithIdentifier:@"pool3"];
        
        cell.arrData = [NSArray arrayWithArray:modle.data];
        
        cell.dicOfType = [NSString stringWithString:modle.sourceData];
        
        return cell;
        
    }
    
    
}




/**区头. */
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {

    Model *model = [self.arrModel objectAtIndex:section];
    
    if (section == 0) {
        
    
        return @"精选";
    }
    
    return model.introduce;  //分区的区头
}

- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
    
    
    
    
    return @"发现生活之美";
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    
    return 200;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    

    
    if (section == self.arrModel.count - 1) {
        
        return 60;
        
    }else {
        
        
        return 0;
    }
    
    
}

#pragma mark -- 轮播图的代理方法.

- (void)Lbtcell:(LbtCell *)SelectedForThisPage :(NSInteger)page {
    
    Model *model = [self.arrModel objectAtIndex:0];
    
    NSDictionary *dic = [model.data objectAtIndex:page];
    
    LbtWebView *web = [[LbtWebView  alloc] init];
    
    
    /**找到底层 VC. 并推出.*/
    id object1 = [self nextResponder];
    while (![object1 isKindOfClass:[UIViewController class]]&&object1!= nil) {
        
        object1 = [object1 nextResponder];
    }
    
    ViewController *VC = (ViewController *)object1;
    
    web.link = [NSString stringWithString:[dic objectForKey:@"linkData"]];
    
    [VC.navigationController pushViewController:web animated:YES];
    
    [web release];
    
}

#pragma mark -- 程序结束时.缓存数据0

- (void)cacheData {
    
    [[NSNotificationCenter defaultCenter] addObserverForName:@"appWillEnd" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        
        NSMutableArray *array = [NSMutableArray array];
        
        for (Model *modle in self.arrModel) {
            
          

            NSMutableData *data = [NSMutableData data];
            
            NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
            
            [archiver encodeObject:modle forKey:@"modle"];
            
            [archiver finishEncoding];
            
            [array addObject:data];
            
        }
            
        NSString *file = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject]stringByAppendingPathComponent:@"cache.plist"];
        
        [array writeToFile:file atomically:YES];
        
      
    }];
    
    
}

- (void)appBegain {
    
    self.arrModel = [NSMutableArray array];
    
    NSString *file = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject]stringByAppendingPathComponent:@"cache.plist"];
    
    
    
    NSArray *array = [NSArray arrayWithContentsOfFile:file];
    
    for (NSData *data in array) {
        
        NSKeyedUnarchiver *unArchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
        
        Model *modle = [unArchiver decodeObjectForKey:@"modle"];
        
        [self.arrModel addObject:modle];
        
        [unArchiver finishDecoding];
        
     
        
        [unArchiver release];
    }
    


    
}


@end
